package com.xgkj.diyiketang.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.PasswordTransformationMethod;
import android.text.style.BackgroundColorSpan;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.EMError;
import com.easemob.chat.EMChatManager;
import com.easemob.exceptions.EaseMobException;
import com.xgkj.diyiketang.util.AppMetaData;
import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.data.EatShowUserInfo;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.security.MD5;
import com.xgkj.diyiketang.task.GetVerifyCodeTask;
import com.xgkj.diyiketang.task.RegisterTask;
import com.xgkj.diyiketang.util.EatShowSetting;
import com.xgkj.diyiketang.util.PalLog;
import com.xgkj.diyiketang.util.ViewUtil;

/**
 * Created by Administrater on 2015/12/9.
 */
public class RegistActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "RegisterActivity";
    private static final int PHONE_LENGTH = 11;
    private static final String PHONE_REGEX = "1[34578]\\d{9}";  //"^1[3|4|5|8][0-9]\\d{8}$ "; //
    private static final int CODE_LENGTH = 6;
    private Context mContext;
    private EditText phoneEdit;
    private EditText codeEdit;
    private EditText pswEdit;
    //    private EditText repswEdit;
    private EditText nickEdit;
    private Button codeButton;
    private Button registerButton;
    private TimeCount time;
    private int getCodeTaskId = -1;
    private int registerTaskId = -1;
    private String localPsw;
    private TextView xieyiBtn;
    private String mPhone;
    private String mCode;
    private String mPsw;
    //    private String mRepeatPsw;
    private String mNickName;
    private TextView back;
    private TextView sexView;
    private PopupWindow mPopWindow;
    private String mSexString;
    private String sexB;
    SpannableString msp = null;
    private String chanelSchool;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.regist);
        mContext = this;
        time = new TimeCount(90000, 1000);
        initView();
    }

    private void initView() {
        back= (TextView) findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        phoneEdit = (EditText) findViewById(R.id.register_phone);
        codeEdit = (EditText) findViewById(R.id.register_code);
        pswEdit = (EditText) findViewById(R.id.register_psw);
        pswEdit.setTransformationMethod(PasswordTransformationMethod.getInstance());
//        repswEdit = (EditText) findViewById(R.id.repeat_psw);
//        repswEdit.setTransformationMethod(PasswordTransformationMethod.getInstance());
        nickEdit = (EditText) findViewById(R.id.regist_nickname);
        codeButton = (Button) findViewById(R.id.code_button);
        registerButton = (Button) findViewById(R.id.register_btn);
        xieyiBtn = (TextView) findViewById(R.id.agree);

        msp = new SpannableString(getText(R.string.register_agree));
        msp.setSpan(new ForegroundColorSpan(mContext.getResources().getColor(R.color.orange_public)), 7, getText(R.string.register_agree).length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        xieyiBtn.setText(msp);
        xieyiBtn.setOnClickListener(this);
        codeButton.setOnClickListener(this);
        registerButton.setOnClickListener(this);
        xieyiBtn.setOnClickListener(this);
        sexView = (TextView) findViewById(R.id.sex);
        sexView.setOnClickListener(this);
        initPopWindow();
    }

    private void initPopWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.choose_sex,null);
        view.findViewById(R.id.nan).setOnClickListener(this);
        view.findViewById(R.id.nv).setOnClickListener(this);
        mPopWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopWindow.setBackgroundDrawable(new ColorDrawable());
        mPopWindow.setFocusable(true);
        mPopWindow.setOutsideTouchable(true);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.code_button:
                if (checkInputBeforeSMS()) {
                    getPhoneCode();
                }
                break;
            case R.id.register_btn:
                if (checkInput()) {
                    doRegister();
                }
                break;
//            case R.id.xieyi:
//                Intent xieyi_intent = new Intent(mContext, WebViewProtocolActivity.class);
//                String url = AppMetaData.getMetaValue(mContext,"HOST_BASE_URL");
//                xieyi_intent.putExtra("url", url+"user_agreement.htm");
//                startActivity(xieyi_intent);
            case R.id.sex:
                mPopWindow.showAtLocation(view, Gravity.BOTTOM,0,30);
                break;
            case R.id.nan:
                sexView.setText(R.string.sex_nan);
                mPopWindow.dismiss();
                break;
            case R.id.nv:
                sexView.setText(R.string.sex_nv);
                mPopWindow.dismiss();
                break;
            case R.id.agree:
//                Intent aIntent = new Intent(mContext,XieYiActivity.class);
//                Intent aIntent = WebViewActivity.getIntent(mContext,"http://www.chiboker.com/yzb/yk.html?vid=XMTQ3MjM1NTYxNg");
//                startActivity(aIntent);
                break;
            default:
                break;
        }
    }

    private void doRegister() {
        String md5Pwd = MD5.digest(mPsw);
        String areaname = EatShowSetting.getInstance(mContext).getFirstLocal();
        String channel = AppMetaData.getMetaValue(mContext, "UMENG_CHANNEL");
        RegisterTask task = new RegisterTask(mPhone,md5Pwd,mCode,mNickName,sexB,"0",areaname,channel);
        task.addListener(new RegisterTaskEventListener(mContext));
        registerTaskId = getEatShowApp().getTaskManager().addTask(task);
    }

    private void getPhoneCode() {
        GetVerifyCodeTask task = new GetVerifyCodeTask(mPhone, "0");
        task.addListener(new RegisterTaskEventListener(mContext));
        getCodeTaskId = getEatShowApp().getTaskManager().addTask(task);
        time.start();
    }

    class RegisterTaskEventListener extends ShowToastTaskEventListener {

        public RegisterTaskEventListener(Context context) {
            super(context);
        }

        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);
            if (taskId == registerTaskId) {
                EatShowSetting.getInstance(mContext).setLoginName(mPhone);
                EatShowSetting.getInstance(mContext).setLoginPsw(localPsw);
                EatShowSetting.getInstance(mContext).setLoginNickname(mNickName);
                if(data!=null){
                    EatShowUserInfo info = (EatShowUserInfo) data;
//                    info.setUserType(0);
//                    info.setCanCreateActivity(false);
                    getEatShowApp().setmUserInfo(info);

                    chanelSchool = info.getSchoolName();
                    if(!TextUtils.isEmpty(chanelSchool)){
                        getEatShowApp().getmUserInfo().setSex(sexB);
                        getEatShowApp().getmUserInfo().setSchoolName(chanelSchool);
                    }

                    final String   HXloginName = info.getUserId();
                    final String HXLoginPdw = "123456";
                    new Thread(new Runnable() {
                        public void run() {
                            try {
                                // 调用sdk注册方法
                                PalLog.e("进入环信注册流程",HXloginName);
                                EMChatManager.getInstance().createAccountOnServer(HXloginName, HXLoginPdw);
                                runOnUiThread(new Runnable() {
                                    public void run() {
                                        if (!RegistActivity.this.isFinishing())
                                            Toast.makeText(getApplicationContext(), getResources().getString(R.string.Registered_successfully), Toast.LENGTH_SHORT).show();
                                        finish();
                                    }
                                });
                            } catch (final EaseMobException e) {
                                runOnUiThread(new Runnable() {
                                    public void run() {

                                        int errorCode=e.getErrorCode();
                                        if(errorCode== EMError.NONETWORK_ERROR){
                                            Toast.makeText(getApplicationContext(), getResources().getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
                                        }else if(errorCode == EMError.USER_ALREADY_EXISTS){
                                            Toast.makeText(getApplicationContext(), getResources().getString(R.string.User_already_exists), Toast.LENGTH_SHORT).show();
                                        }else if(errorCode == EMError.UNAUTHORIZED){
                                            Toast.makeText(getApplicationContext(), getResources().getString(R.string.registration_failed_without_permission), Toast.LENGTH_SHORT).show();
                                        }else if(errorCode == EMError.ILLEGAL_USER_NAME){
                                            Toast.makeText(getApplicationContext(), getResources().getString(R.string.illegal_user_name),Toast.LENGTH_SHORT).show();
                                        }else{
                                            Toast.makeText(getApplicationContext(), getResources().getString(R.string.Registration_failed) + e.getMessage(), Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                });
                            }
                        }
                    }).start();

                }
//                Intent intent = new Intent(mContext, MainActivity.class);
                Intent intent = new Intent(mContext, WanshanziliaoActivity.class);
                intent.putExtra("school",chanelSchool);
                startActivity(intent);
                finish();
            }
        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            super.handleTaskError(taskId, errorCode, errorMsg);
            if (taskId == getCodeTaskId) {
                time.cancelTime();
            }
        }

    }

    private boolean checkInputBeforeSMS() {
        mPhone = phoneEdit.getText().toString();
        if (TextUtils.isEmpty(mPhone) || mPhone.length() != PHONE_LENGTH
                || !mPhone.matches(PHONE_REGEX)) {
            Toast.makeText(mContext, R.string.no_phone, Toast.LENGTH_SHORT)
                    .show();
            return false;
        }
        return true;
    }

    private boolean checkInput() {
        mCode = codeEdit.getText().toString();
        mPsw = pswEdit.getText().toString();
//        mRepeatPsw = repswEdit.getText().toString();
        mNickName = nickEdit.getText().toString();
        mSexString = sexView.getText().toString();
        if (mSexString.equals("男")){
            sexB = "true";
        }else{
            sexB = "false";
        }
        if (checkInputBeforeSMS()) {
            if (TextUtils.isEmpty(mPsw)) {
                Toast.makeText(mContext, R.string.no_psw, Toast.LENGTH_SHORT)
                        .show();
                return false;
            }
//            else if (!mPsw.equals(mRepeatPsw)) {
//                Toast.makeText(mContext, R.string.not_same_psw,
//                        Toast.LENGTH_SHORT).show();
//                return false;
//            }
            else if (TextUtils.isEmpty(mCode)
                    || mCode.length() != CODE_LENGTH) {
                Toast.makeText(mContext, R.string.no_code, Toast.LENGTH_SHORT)
                        .show();
                return false;
            } else if (TextUtils.isEmpty(mNickName)) {
                Toast.makeText(mContext, R.string.no_nick,Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        return true;
    }

    /**
     * 方法作用：倒计时
     */
    class TimeCount extends CountDownTimer {

        // 参数依次为总时长,和计时的时间间隔
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {// 计时完毕时触发
            codeButton.setText(mContext.getString(R.string.get_vfcode));
            codeButton.setClickable(true);
            codeButton.setEnabled(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
            codeButton.setClickable(false);
            codeButton.setEnabled(false);
            codeButton.setText(String.format(
                    mContext.getString(R.string.get_vfcode_new),
                    millisUntilFinished / 1000));
        }

        public void cancelTime() {// 取消计时
            time.cancel();
            codeButton.setText(mContext.getString(R.string.get_vfcode));
            codeButton.setClickable(true);
            codeButton.setEnabled(true);
        }

    }
}
